package com.mzy.interview

import java.util.*
import kotlin.collections.ArrayDeque

class 逆波兰表达式() {
    private val stack = Stack<String>()
    fun evalRPN(tokens: Array<String>): Int {
        var ans: Int = 0
        for (i in 0..<tokens.size) {
            if (tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/") {
                stack.push(tokens[i])
                continue
            }
            val left = stack.pop()!!.toInt()
            val right = stack.pop()!!.toInt()
            if (tokens[i] == "+") {
                ans = right + left
            } else if (tokens[i] == "-") {
                ans = right - left
            } else if (tokens[i] == "/") {
                ans = right / left
            } else if (tokens[i] == "*") {
                ans = right * left
            }
            stack.push(ans.toString())
        }
        return if (stack.isEmpty()) 0 else stack.pop().toInt();
    }
}

fun main(args: Array<String>) {
    val param = arrayOf("2", "1", "+", "3", "*")
    val stack = Stack<String>()
    println(逆波兰表达式().evalRPN(param))
}